import { Controller, UseInterceptors, UploadedFile, Get, Post, Body, Param, ParseUUIDPipe, Res, Put } from '@nestjs/common'
import { FileInterceptor } from '@nestjs/platform-express'
import { AvatarService } from './avatar.service'
import { CreateAvatarDto } from './dto/create-avatar.dto'
import { Response } from 'express'
import { Public } from '@/decorator/public.decorator'

@Controller('avatar')
export class AvatarController {
  constructor(private readonly avatarService: AvatarService) {}

  @Post('upload')
  @UseInterceptors(FileInterceptor('file'))
  uploadAvatar(@UploadedFile() file: Express.Multer.File, @Body() createAvatarDto: CreateAvatarDto) {
    return this.avatarService.create(file, createAvatarDto)
  }

  @Get(':uid')
  @Public()
  async findOne(@Param('uid', ParseUUIDPipe) uid: string, @Res() res: Response) {
    const image = await this.avatarService.findOne(uid)
    res.set({
      'Content-Type': image.contentType,
      'Content-Length': image.avatar.length
    })
    res.send(image.avatar)
  }

  @Put(':uid')
  @UseInterceptors(FileInterceptor('file'))
  changeAvatar(@UploadedFile() file: Express.Multer.File, @Param('uid', ParseUUIDPipe) uid: string) {
    return this.avatarService.changeAvatar(file, uid)
  }
}
